package core;

import java.io.File;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import org.xml.sax.SAXException;

import tournamentData.TournamentData;
import dataBase.DbHolder;

public class AutoSaver implements Observer {
	private static AutoSaver instance = null;;
	private boolean autoSave;
	private long lastSaveTime;

	private AutoSaver() {
		this.autoSave = false;
		TournamentData.getInstance().addObserver(this);
		DbHolder.getInstance().getArcherData().addObserver(this);
		TournamentData.getInstance().getTargetAssignment().addObserver(this);
	}

	public static AutoSaver getInstance() {
		if (instance == null) {
			instance = new AutoSaver();
		}
		return instance;
	}

	public void setAutoUpdate(boolean autoUpdate) {
		this.autoSave = autoUpdate;
	}

	private void saveTournamentData() {
		try {
			XMLWriter.writeToFile(new File(XMLWriter.getFileName(TournamentData.getInstance().getGeneralTournamentInformation().getTournamentName(), TournamentData.getInstance()
					.getGeneralTournamentInformation().getStartDate())));
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void save() {
		if (this.autoSave) {
			long currentTime = System.currentTimeMillis();

			if ((currentTime - this.lastSaveTime) > 1000) {
				this.saveTournamentData();
				this.lastSaveTime = System.currentTimeMillis();
			}
		}
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		this.save();
	}
}
